<template>
  <th
    class="table-cell header-cell"
    :class="{ 'is-editing': editing, 'is-required': field.required, 'is-error': data.isSet && !field.label }"
    @dblclick="data.isSet && (editing = true)"
  >
    <CellEditor
      v-model="field.label"
      type="input"
      :editing.sync="editing"
      :maxlength="maxlength"
      :height="data.isHorizontalTable ? data.tableOptions.headerHeight : data.tableOptions.rowHeight"
      @tab="tabFocus"
    />

    <!-- 设置中 -->
    <template v-if="data.isSet">
      <!-- 扩展字段数据 -->
      <TableHandle :data="data" :field-index="index" />

      <!-- 隐藏表头 -->
      <TableHandle v-if="!index" :data="data" />
    </template>
  </th>
</template>

<script lang="ts">
import { computed, defineComponent, inject, PropType, toRef } from 'vue'
import config from '@/config'
import { Widget } from '@/models'
import { TableEditState, TableField } from '@/types'
import CellEditor from './CellEditor.vue'
import TableHandle from './TableHandle.vue'
import { useFieldActiveIndex } from '../utils'

export default defineComponent({
  name: 'HeaderCell',

  components: { CellEditor, TableHandle },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 字段 */
    field: {
      type: Object as PropType<TableField>,
      required: true
    },

    /** 索引 */
    index: {
      type: Number,
      required: true
    }
  },

  setup(props) {
    const state = inject('TableEditState') as TableEditState

    /** 当前激活表格项 index */
    const activeIndex = useFieldActiveIndex(toRef(props, 'data'))

    /** 编辑状态 */
    const editing = computed({
      get() {
        const { index } = props

        return index === state.headerIndex
      },

      set(val) {
        const { index } = props

        if (val) {
          state.headerIndex = index
          activeIndex.value = index
        } else if (editing.value) {
          state.headerIndex = -1
        }
      }
    })

    return {
      /** 编辑状态 */
      editing,

      /** 最大输入长度 */
      maxlength: config.tableOption.fieldLabelMaxLength,

      /** Tab 键聚焦编辑 */
      tabFocus(e: MouseEvent) {
        const isNext = !e.shiftKey

        let {
          index,
          data: { tableFields }
        } = props
        const indexMax = tableFields.length - 1

        if (isNext) {
          if (index < indexMax) {
            index++
          } else {
            index = 0
          }
        } else {
          if (index > 0) {
            index--
          } else {
            index = indexMax
          }
        }

        Object.assign(state, { headerIndex: index })
      }
    }
  }
})
</script>

<style lang="scss">
.fa-widget-table-main .header-cell {
  // 使用透明背景，避免 firefox 浏览器表头边框缺失
  background-color: rgba(0, 0, 0, 0.04);

  &.is-required .cell-text::after {
    margin-left: 3px;
    color: $color-danger;
    font-weight: 400;
    font-size: 12px;
    vertical-align: text-top;
    content: '*';
  }
}
</style>
